package com.aiserver.config;

import com.aiserver.interceptor.JwtAuthenticationInterceptor;
import com.aiserver.interceptor.EncryptionInterceptor;
import com.aiserver.interceptor.RateLimitInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web配置类
 * 配置拦截器、跨域等
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private JwtAuthenticationInterceptor jwtAuthenticationInterceptor;

    @Autowired
    private EncryptionInterceptor encryptionInterceptor;

    @Autowired
    private RateLimitInterceptor rateLimitInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 限流拦截器 - 最先执行
        registry.addInterceptor(rateLimitInterceptor)
                .addPathPatterns("/**");

        // 加密拦截器 - 处理请求和响应的加密解密
        registry.addInterceptor(encryptionInterceptor)
                .addPathPatterns("/**");

        // JWT认证拦截器
        registry.addInterceptor(jwtAuthenticationInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/auth/login",
                        "/auth/sms-login",
                        "/auth/wechat-login",
                        "/auth/wechat-auth-url",
                        "/auth/wechat/callback",
                        "/auth/register",
                        "/auth/send-sms-code",
                        "/auth/captcha",
                        "/auth/verify-captcha",
                        "/auth/refresh-token",
                        "/error",
                        "/favicon.ico"
                );
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}